<style lang="less">
.category-tree {
    & {
        min-width: 100%;
        min-height: 100%;
        padding: 0 10px;
        overflow: auto;
    }
    .row-title{
        margin-right: 10px;
    }
}
</style>
<template>
    <div class="category-tree">
        <a-tree :default-expand-all="false" :blockNode="true" :selected-keys="selectedKeys" :tree-data="treeData" :expandedKeys="expandedKeys" :draggable="false" @select="onTreeSelect" @expand="onExpand">
            <template slot="custom" slot-scope="item">
                <div v-if="hasOper">
                    <div v-if="!item.isRoot">
                        <span class="row-title">{{ item.title }}</span>
                        <a-dropdown class="tree-dropdown" :trigger="['hover']" >
                            <a-icon type="menu-unfold"/>
                            <a-menu slot="overlay" class="dc-tree-dropdown-menus">
                                <a-menu-item key="4" @click="upNode(item)" :disabled="item.isFirst">上移</a-menu-item>
                                <a-menu-divider/>
                                <a-menu-item key="5" @click="downNode(item)" :disabled="item.isLast">下移</a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <div v-else>
                        <span>{{ item.title }}</span>
                    </div>
                </div>
                <div v-else>
                    <span>{{ item.title }} </span>
                </div>
            </template>
        </a-tree>
    </div>
</template>
<script>
/** 客户树组件 */
import { queryCustomerTree,updateCustomerTreeSort } from '@/api/customer';
export default {
    components: {
    },
    props: {
        /** 类型 0.普通 1. 1级以下客户选择上级客户 */
        type: {
            type: Number,
            require: true
        },
        /** 是否有操作功能 */
        hasOper: {
            type: Boolean,
            default: () => false
        },
        title: {
            type: String,
            default: () => null
        },
        rootKey: {
            type: String,
            default: () => '0'
        },
        /** 当前选中的 key */
        nowKey: {
            type:String,
            default: () => ''
        }
    },
    data() {
        return {
            // 选中的
            selectedKeys: [],
            // 状态树
            treeData: [],
            // 展开的树节点
            expandedKeys: [],
        }
    },
    async created() {
        await this.refresh();
        this.expandedKeys = [this.rootKey];
    },
    methods: {
        async refresh() {
            let title = '所有客户';
            if(this.type==1){
                const arr = await queryCustomerTree({ parentId: 0 }) || [];
                const arr1 = nodeDataToVMNodeData(arr,this);
                //  从一级节点树下查询有传入节点的一级节点
                const node = arr1.find(i=> queryNodeInTree(this.nowKey,i)||i.key==this.nowKey);
                if(node){
                    node.isRoot  = true;
                    this.treeData = [
                       node
                    ];
                }else{
                    this.treeData = [
                       {
                            title,
                            key: this.rootKey,
                            scopedSlots: {
                                title: 'custom',
                            },
                            isRoot: true,
                            children: arr1
                        }
                    ];
                }
                return;
            }
            let arr = await queryCustomerTree({ parentId: 0 }) || [];
            this.treeData = [
                {
                    title,
                    key: this.rootKey,
                    scopedSlots: {
                        title: 'custom',
                    },
                    isRoot: true,
                    children: nodeDataToVMNodeData(arr,this)
                }
            ];
        },
        onTreeSelect(selectedKeys, e) {
            this.setTreeSelected(selectedKeys);
            if (e.selected) {
                this.$emit('selected', e.node.dataRef);
            } else {
                this.$emit('selected', null);
            }
        },
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys;
        },
        setTreeSelected(selectedKeys) {
            this.selectedKeys = [...selectedKeys];
            if (selectedKeys.length > 0 && selectedKeys[0] == 0) {
                selectedKeys[0] = null;
            }
        },
       
        async upNode(item) {
            const res = queryNodeInTree(item.key, { children: this.treeData });
            if (!res) {
                throw Error('未找到节点！', item);
            }
            const arr = res.pNode.children;
            const index = arr.findIndex(i => i.key == item.key);
            const node = arr[index];
            const preNode = arr[index - 1];

            await updateCustomerTreeSort({
                changeId1: node.key,
                changeId2: preNode.key
            });
            // 对调两节点位置
            let { isFirst, isLast } = preNode;
            preNode.isFirst = node.isFirst;
            preNode.isLast = node.isLast;
            node.isFirst = isFirst;
            node.isLast = isLast;
            arr[index] = preNode;
            arr[index - 1] = node;
            this.expandedKeys = [...this.expandedKeys];
        },
        async downNode(item) {
            const res = queryNodeInTree(item.key, { children: this.treeData });
            if (!res) {
                throw Error('未找到节点！', item);
            }
            const arr = res.pNode.children;
            const index = arr.findIndex(i => i.key == item.key);
            const node = arr[index];
            const nextNode = arr[index + 1];
            await updateCustomerTreeSort({
                changeId1: node.key,
                changeId2: nextNode.key
            });

            // 对调两节点位置
            let { isFirst, isLast } = nextNode;
            nextNode.isFirst = node.isFirst;
            nextNode.isLast = node.isLast;
            node.isFirst = isFirst;
            node.isLast = isLast;
            arr[index] = nextNode;
            arr[index + 1] = node;
            this.expandedKeys = [...this.expandedKeys];
        }
    }
}
/**
 * 节点数据转换为视图节点数据
 * @param {Array} nodeDatas
 */
function nodeDataToVMNodeData(nodeDatas,ctx,parentNodeData) {
    return nodeDatas.map((i, index) => {
        // 选择上一级,用户也可以自主选择【上级公司】，只能在同集团中选择,不能选择【法人客户】作为上级客户
        const disabled = ctx.type == 1 && (i.customerCategory==3||i.customerCategory==4)?true:false;
        Object.assign(i, {
            title: i.status==2?`${i.customerName}（审批中）`: i.customerName,
            key: i.id,
            scopedSlots: { title: 'custom' },
            isFirst: index == 0 ? true : false,
            isLast: index == nodeDatas.length - 1 ? true : false,
            disabled,
            pathText:`${parentNodeData?parentNodeData.pathText+'-':''}${i.customerName}`
        });
        if (i.children) {
            i.children = nodeDataToVMNodeData(i.children,ctx,i);
        }
        return i;
    })
}

/**
 * 树中查询节点
 * @returns {{
        node: item,
        pNode: tree
   }}
 */
function queryNodeInTree(key, tree) {
    if (!tree.children) {
        return null;
    }
    if (tree.children.length == 0) {
        return null;
    }
    const item = tree.children.find(i => i.key == key);
    if (item) {
        return {
            node: item,
            pNode: tree
        };
    }
    const arr = tree.children.map(i => queryNodeInTree(key, i));
    return arr.find(i => i != null);
}
</script>